package xin.nick.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import xin.nick.config.SystemConstants;

import java.util.ArrayList;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 权限检查
 * @author Nick
 * @since 2023/1/14/014
 */
@Component
public class WebSecurity {

    /**
     * 检查是否有权限
     * @param authorityList
     * @return
     */
    public boolean check(String... authorityList) {

        Set<String> authoritySet = getAuthoritySet();
        for (String authority : authorityList) {
            // 如果是root用户,可以直接操作
            if (authoritySet.contains(SystemConstants.ROOT_ROLE)) {
                return true;
            }
            // 存在权限则可以操作
            if (authoritySet.contains(authority)) {
                return true;
            }
        }
        return false;

    }

    /**
     * 获取当前用户权限Set
     * @return
     */
    private Set<String> getAuthoritySet() {

        return Optional.ofNullable(SecurityContextHolder.getContext())
                .map(SecurityContext::getAuthentication)
                .map(Authentication::getAuthorities)
                .orElse(new ArrayList<>())
                .stream()
                .filter(Objects::nonNull)
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toSet());
    }

}
